import { useState, useEffect } from 'react';
import moment from 'moment';
import { connect } from 'umi';
import { Modal, Button, Spin, Radio, DatePicker } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { useTablePipeline } from 'ali-react-table';
import { TjTable } from '@/pages/ETrade/components';
import { useTRState } from '#/utils/trHooks.jsx';
import styles from './index.less';
import planIcon from '@/assets/img/plan_icon.png';
import planIconDark from '@/assets/img/plan_icon_dark.png';
import planIconGre from '@/assets/img/plan_icon_gre.png';
import {
  getDayaheadConfig,
  getHolidayByYear,
  saveDayaheadConfig,
  deleteHolidayConfig,
} from '../../services';
import { HttpCode } from '#/utils/contacts';
import { windowsOptions } from '../../constant';
import { getColumns, generalRequiredFields, holidayRequiredFields } from './helper';
import { TRDefault } from '@/components';
import emitter from '#/utils/events';

const WindowPeriodConfiguration = ({ marketId, provinceId }) => {
  const [modal, contextHolder] = Modal.useModal();
  const [theme, setTheme] = useState(localStorage.getItem('saas-theme') || 'dark');
  const [state, setState] = useTRState({
    visible: false,
    tableData: [],
    time: moment().format('YYYY'),
    loading: false,
    type: '1',
  });

  useEffect(() => {
    emitter.addListener('onGlobalThemeChange', (e) => {
      setTheme(e.key);
    });
    return () => {
      emitter.removeListener('onGlobalThemeChange', () => {});
    };
  }, []);

  const attachMeta = (data) =>
    data.map((item) => ({
      ...item,
      type: state.type,
      marketId,
      provinceId,
      year: state.type === '1' ? '' : state.time,
    }));

  const fetchData = async (value = '1') => {
    setState({ tableData: [], loading: true });
    const params = {
      type: value || state.type,
      marketId,
      year: value === '1' ? moment().format('YYYY') : state.time,
    };
    const res = await getDayaheadConfig(params);
    if (res.statusCode === HttpCode.SUCCESS) {
      const dataWithKey = (res.data || []).map((item, idx) => ({
        ...item,
        key: idx,
      }));
      setState({ tableData: dataWithKey, loading: false });
    }
  };

  const getHoliday = async () => {
    setState({ loading: true });
    try {
      const res = await getHolidayByYear(marketId, state.time);
      if (res.statusCode === HttpCode.SUCCESS) {
        const validData = state.tableData.filter(
          (item) => item.holidayName && item.holidayName.trim() !== '',
        );
        const existNames = new Set(validData.map((item) => item.holidayName));
        const mergedData = [
          ...validData,
          ...(res.data || []).filter(
            (item) => item.holidayName && !existNames.has(item.holidayName),
          ),
        ];
        const dataWithKey = mergedData.map((item, idx) => ({
          ...item,
          key: idx,
        }));
        setState({ tableData: dataWithKey, loading: false });
      } else {
        throw new Error(res.message || '获取节假日信息失败，请稍后再试。');
      }
    } catch (err) {
      modal.error({
        title: '获取节假日失败',
        content: err.message,
      });
      setState({ loading: false });
    }
  };

  const onHolidayAdd = () => {
    const maxKey = state.tableData.length
      ? Math.max(...state.tableData.map((item) => Number(item.key ?? 0)), 0)
      : 0;
    const newKey = maxKey + 1;

    let newRow = {};
    if (state.type === '2') {
      newRow = {
        key: newKey,
        holidayName: '',
        holidayStartDate: moment().format('YYYY-MM-DD'),
        holidayEndDate: moment().format('YYYY-MM-DD'),
        startTime: null,
        endTime: null,
        days: 0,
      };
    }
    setState({ tableData: [...state.tableData, newRow] });
  };

  const onHolidayDel = (data) => {
    if (data.id) {
      setState({ loading: true });
      deleteHolidayConfig(data.id)
        .then((res) => {
          if (res.statusCode === HttpCode.SUCCESS) {
            const newData = state.tableData.filter((item) => item.key !== data.key);
            setState({ tableData: newData, loading: false });
            modal.success({
              title: '删除成功',
              content: '节假日已成功删除。',
            });
          } else {
            modal.error({
              title: '删除失败',
              content: res.message || '删除节假日失败，请稍后再试。',
            });
            setState({ loading: false });
          }
        })
        .catch((err) => {
          modal.error({
            title: '删除失败',
            content: err.message || '删除节假日失败，请稍后再试。',
          });
          setState({ loading: false });
        });
    } else {
      const newData = state.tableData.filter((item) => item.key !== data.key);
      setState({ tableData: newData });
    }
  };

  const onTableContentChange = (val, record, type) => {
    if (state.type === '2') {
      if (type === 'holidayRange') {
        const newData = state.tableData.map((item) =>
          item.key === record.key
            ? {
                ...item,
                holidayStartDate: val[0].format('YYYY-MM-DD'),
                holidayEndDate: val[1].format('YYYY-MM-DD'),
              }
            : item,
        );
        setState({ tableData: newData });
      } else {
        const newData = state.tableData.map((item) =>
          item.key === record.key ? { ...item, [type]: val } : item,
        );
        setState({ tableData: newData });
      }
    } else {
      const newData = state.tableData.map((item) =>
        item.key === record.key ? { ...item, [type]: val } : item,
      );
      setState({ tableData: newData });
    }
  };

  const onTypeChange = ({ target: { value } }) => {
    setState({ type: value });
    fetchData(value);
  };

  const onYearChange = (date, dateString) => {
    setState({ time: dateString });
  };

  const onCancel = () => {
    modal.confirm({
      title: '数据未保存，确定关闭吗？',
      icon: <ExclamationCircleOutlined />,
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        setState({ visible: false, type: '1', tableData: [] });
      },
    });
  };

  const onSave = () => {
    if (state.tableData.length === 0) {
      modal.error({
        title: '请先配置日前窗口期',
        content: '请先配置日前窗口期',
      });
      return;
    }

    if (state.type === '1') {
      for (let i = 0; i < state.tableData.length; i++) {
        const row = state.tableData[i];
        for (const field of generalRequiredFields) {
          if (row[field.key] === undefined || row[field.key] === null || row[field.key] === '') {
            modal.error({
              title: '必填项校验失败',
              content: `第${i + 1}行【${field.label}】不能为空，请填写完整后再保存。`,
            });
            return;
          }
        }
      }

      // tradeWeek（标定日）唯一性校验
      const tradeWeekSet = new Set();
      for (let i = 0; i < state.tableData.length; i++) {
        const row = state.tableData[i];
        if (tradeWeekSet.has(row.tradeWeek)) {
          modal.error({
            title: '标定日重复',
            content: `第${i + 1}行标定日已存在，请勿重复填写。`,
          });
          return;
        }
        tradeWeekSet.add(row.tradeWeek);
      }
    }
    if (state.type === '2') {
      for (let i = 0; i < state.tableData.length; i++) {
        const row = state.tableData[i];
        for (const field of holidayRequiredFields) {
          if (row[field.key] === undefined || row[field.key] === null || row[field.key] === '') {
            modal.error({
              title: '必填项校验失败',
              content: `第${i + 1}行【${field.label}】不能为空，请填写完整后再保存。`,
            });
            return;
          }
        }
      }
      // 节假日名称重复校验
      const nameSet = new Set();
      /* for (let i = 0; i < state.tableData.length; i++) {
        const row = state.tableData[i];
        if (nameSet.has(row.holidayName)) {
          modal.error({
            title: '节假日名称重复',
            content: `第${i + 1}行节假日名称已存在，请勿重复填写。`,
          });
          return;
        }
        nameSet.add(row.holidayName);
      } */

      let hasDuplicate = false;
      const newData = state.tableData.map((item) => {
        if (!item.holidayName) return item;
        if (nameSet.has(item.holidayName)) {
          hasDuplicate = true;
          return { ...item, holidayName: '' };
        }
        nameSet.add(item.holidayName);
        return item;
      });
      if (hasDuplicate) {
        setState({ tableData: newData });
        modal.error({
          title: '节假日名称重复',
          content: '存在重复的节假日名称，已自动清空重复项，请检查后再保存。',
        });
        return;
      }
    }

    // 保存逻辑
    const dataToSave =
      state.type === '1' ? state.tableData.map(({ id, ...rest }) => rest) : state.tableData;

    saveDayaheadConfig(attachMeta(dataToSave)).then((res) => {
      if (res.statusCode === HttpCode.SUCCESS) {
        modal.success({
          title: '保存成功',
          content: '日前窗口期配置已保存',
          onOk: async () => {
            setState({ visible: false, type: '1', tableData: [] });
          },
        });
      } else {
        modal.error({
          title: '保存失败',
          content: res.message || '保存日前窗口期配置失败，请稍后再试。',
        });
      }
    });
  };

  const pipeline = useTablePipeline({})
    .input({
      columns: getColumns({ onHolidayAdd, onHolidayDel, type: state.type, onTableContentChange }),
      dataSource: state.tableData,
    })
    .primaryKey('id');

  return (
    <>
      <Modal
        className={styles.model_detail}
        centered={true}
        title={
          <div className={styles.modalTitle}>
            <img src={theme === 'dark' ? planIconDark : theme === 'gre' ? planIconGre : planIcon} />
            <span className={styles.text}>日前窗口期配置</span>
          </div>
        }
        footer={null}
        visible={state.visible}
        onCancel={onCancel}
      >
        <Spin spinning={state.loading}>
          <div className={styles.flex_row}>
            <Radio.Group
              className={styles.radioGroup}
              options={windowsOptions}
              onChange={onTypeChange}
              value={state.type}
              optionType="button"
              buttonStyle="solid"
            />
            <div className={styles.right_info}>
              <DatePicker
                className={state.type === '1' ? styles.btnDis : ''}
                onChange={onYearChange}
                picker="year"
                value={state.time ? moment(state.time, 'YYYY') : null}
                allowClear={false}
              />
              <Button className={state.type === '1' ? styles.btnDis : ''} onClick={getHoliday}>
                获取节假日
              </Button>
              <Button onClick={onCancel}>取消</Button>
              <Button
                /* onClick={() => {
                  modal.confirm({
                    title: '数据未保存，确认还原吗？',
                    icon: <ExclamationCircleOutlined />,
                    okText: '确认',
                    cancelText: '取消',
                    onOk: () => {
                      setState({ loading: true });
                      fetchData(state.type);
                    },
                  });
                }} */
                onClick={() => {
                  setState({ loading: true });
                  fetchData(state.type);
                }}
              >
                还原
              </Button>
              <Button type="primary" onClick={onSave}>
                保存
              </Button>
            </div>
          </div>
          {state.tableData.length === 0 ? (
            <TRDefault type="emptysm" />
          ) : (
            <TjTable
              className={styles.tableBox}
              style={{
                '--header-row-height': '36px',
                '--font-size': '12px',
                '--cell-padding': '4px 5px',
                marginTop: '20px',
                borderRadius: '5px',
              }}
              useOuterBorder={true}
              stickyScrollHeight={10}
              useVirtual={{ horizontal: true, vertical: true, header: false }}
              defaultColumnWidth={100}
              {...pipeline.getProps()}
            />
          )}
        </Spin>
      </Modal>
      <Button
        onClick={() => {
          setState({ visible: true, loading: true });
          fetchData('1');
        }}
      >
        窗口期配置
      </Button>
      {contextHolder}
    </>
  );
};
export default connect(({ interprovincialSpotDeclaration }) => ({
  provinceId: interprovincialSpotDeclaration.provinceId,
  marketId: interprovincialSpotDeclaration.marketId,
}))(WindowPeriodConfiguration);
